package com.kaikeba.web;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

/**
 * 功能：处理文件上传请求
 */
@WebServlet("/fileUpload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、创建上传文件对象
        SmartUpload su = new SmartUpload();
        //2、初始化上传操作
        /**
         * getPageContext( )参数说明：
         *  第一个参数：servlet对象
         *  第二个参数：请求对象
         *  第三个参数：响应对象
         *  第四个参数：字符串 jsp的错误页面
         *  第五个参数：布尔值 是否使用session
         *  第六个参数：单位是kb 缓冲区的大小
         *  第七个参数：用于决定缓冲区满了，是否输出到到输出流中
         */
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this,req,resp,null,false,1024,true);
        su.initialize(pageContext);
        //3、设置编码
        su.setCharset("UTF-8");
        try {
            //4、上传
            su.upload();
            //注意：必须要在上传之后，才能获取表单的其它项文本信息
            String describe = su.getRequest().getParameter("describe");
            System.out.println("describe:"+describe);
            //5、将上传的文件创建为文件对象
            File file = su.getFiles().getFile(0);
            //6、获取文件名称、类型
            String fileName = file.getFileName();
            System.out.println("FileName:"+fileName);
            String contentType = file.getContentType();
            //7、指定上传的路径
            String path = "/uploadFiles/"+fileName;
            //8、保存到指定路径
            file.saveAs(path,File.SAVEAS_VIRTUAL);
            //9、跳转到成功页面
            req.setAttribute("filename",fileName);
            req.getRequestDispatcher("Success.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}
